<template>
  <view class="cropper_popup">
    <template v-if="isLoad">
      <image-cropper
        ref="imageCropper"
        :limit_move="true"
        :disable_rotate="true"
        :disable_ratio="true"
        :width="cropperWidth"
        :height="cropperHeight"
        :quality="1"
        :imgSrc="imgSrc"
        :cut_top="cutTop"
        :cut_left="cutLeft"
        :fixed_height="true"
        :fixed_width="true"
      ></image-cropper>
    </template>
    <view class="btns">
      <view @click="handleCancel">取消</view>
      <view class="sure u-center" @click="handleSure">确认</view>
    </view>
  </view>
</template>
<script>
import { ossConfig } from '@/utils/alioss.js'
import { storage } from '@/utils/utils'
import { SAVE_DEFAULT_AVATAR, SAVE_COMMON_IMAGE, SAVE_COMMON_PET_IMAGE_SHOW, SAVE_LVPISHU_IMAGE_SHOW } from '@/assets/js/config'

export default {
  data () {
    return {
      imgSrc: '',
      isLoad: false,
      orgin: '',
      cutTop: null,
      cutLeft: null,
      cropperWidth: 320,
      cropperHeight: 320
    }
  },
  onLoad (options) {
    this.imgSrc = decodeURIComponent(options.path)
    this.isLoad = true
    this.orgin = options.orgin
    if (options.w) {
      this.cropperWidth = options.w
    }
    if (options.h) {
      this.cropperHeight = options.h
    }
    this.cutLeft = (uni.getSystemInfoSync().windowWidth - this.cropperWidth) / 2
    this.cutTop = (uni.getSystemInfoSync().windowHeight - this.cropperHeight) / 2
    // console.log(999, this.cropperWidth, this.cropperHeight, this.cutLeft, this.cutTop)
  },
  methods: {
    handleCancel () {
      uni.navigateBack({ delta: 1 })
    },
    handleSure () {
      // getImg获取裁剪后的图片信息
      uni.showLoading({
        title: '剪切中...'
      })
      this.$refs.imageCropper.getImg(async res => {
        const path = res.url
        ossConfig(path).then(res => {
          if (this.orgin === 'first') {
            storage.set(SAVE_DEFAULT_AVATAR, res.substr(24))
          }
          if (this.orgin === 'edid') {
            storage.set(SAVE_COMMON_IMAGE, res.substr(24))
          }
          if (this.orgin === 'petImg') {
            storage.set(SAVE_COMMON_PET_IMAGE_SHOW, res.substr(24))
          }
          if (this.orgin === 'lvpishu') {
            storage.set(SAVE_LVPISHU_IMAGE_SHOW, res)
          }
          uni.navigateBack({ delta: 1 })
        }).catch(() => {
          uni.hideLoading()
          uni.showToast({
            title: '请检查网络',
            icon: 'none'
          })
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.cropper_popup {
  width: 100%;
  height: 100vh;
  position: relative;
  .btns {
    width: 100%;
    padding: 0 40rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    bottom: 80rpx;
    z-index: 999999;
    color: #fff;
    font-size: 28rpx;
  }
  .sure{
    width: 120rpx;
    height: 66rpx;
    background: #F0831E;
    border-radius: 100px;
  }
}
</style>
